﻿'use strict';

resumeApp.controller('personalInfoEditCtrl', ['$scope', '$routeParams', '$window', 'personalInfoService',
    function ($scope, $routeParams, $window, personalInfoService) {
    $scope.personalInfo = {};
    $scope.title = 'Edit';
    $scope.buttonText = 'Update';

    init();

    function init() {
        var id = ($routeParams.id) ? parseInt($routeParams.id) : 0;
        if (id > 0) {
            personalInfoService.getPersonalInfo(id)
                .then(function (personalInfo) {
                    $scope.personalInfo = personalInfo;
                    //dataService.apply($scope); //Handles calling $apply() if needed (mainly for breeze since it's a 3rd party library)
                }, function(status) {
                    console.log("error:" + status);
                });
        }
        else {
            $scope.title = 'Add';
            $scope.buttonText = 'Add';
        }
    }

    $scope.updatePersonalInfo = function (personalInfo, personalInfoEditForm) {

        if (personalInfoEditForm.$valid) {

            if (personalInfo.Id === undefined) {
                personalInfoService.addPersonalInfo(personalInfo)
                    .then(function() {
                        // success
                        $window.location = "#/personalInfos";
                    },
                        function() {
                            // error
                            alert("could not save the new personal info");
                        });
            } else {
                personalInfoService.updatePersonalInfo($scope.personalInfo)
                    .then(function () {
                        // success
                        $window.location = "#/personalInfos";
                    },
                        function () {
                            // error
                            alert("could not update personal info");
                        });
            }
        }
    };
}]);